package it.softphone.cmc.server.service.impl;


import it.softphone.cmc.server.service.TenantService;
import it.softphone.cmc.server.service.exception.CMCException;
import it.softphone.commons.exception.NullParameterException;

import com.google.appengine.api.NamespaceManager;

public class GAETenantServiceImpl implements TenantService {


	@Override
	public String getCurrentTenant() {
		return NamespaceManager.get();
	}

	@Override
	public void updateToSystemTenant() {
		NamespaceManager.set( NamespaceManager.getGoogleAppsNamespace() );		
	}

	@Override
	public String getSystemTenant() {
		return NamespaceManager.getGoogleAppsNamespace();
	}

	@Override
	public void setTenant(String tenant) {
		if( tenant==null ) {
			//TODO warn this condition
			return;
		}
		
		NamespaceManager.validateNamespace(tenant);
		NamespaceManager.set( tenant );
	}

	@Override
	public <T> T execAsSystemTenant(Task<T> task) throws CMCException {
		
		return execAsTenant( getSystemTenant(), task );
	}

	@Override
	public <T> T execAsTenant(String tenant, Task<T> task) throws CMCException {
		if( tenant == null ) throw new NullParameterException("tenant");
		if( task == null ) throw new NullParameterException("task");
		
		final String prevTenant = NamespaceManager.get();
		
		NamespaceManager.validateNamespace(tenant);
		NamespaceManager.set( tenant );
		
		
		try {
			return (T)task.exec();
			
		} catch (Exception e) {

			throw new CMCException(e);
		}
		finally {
			NamespaceManager.set( prevTenant );
			
		}
	}

}

